<template>
  <div class="product-list">
    <el-collapse class="collapse">
      <el-collapse-item title="商品管理介绍">
        <div>
          商品管理模块可以对客户端的商品进行增删改查等相关操作,来控制客户端商品的列表展示和商品详情
        </div>
      </el-collapse-item>
    </el-collapse>

    <div class="collapse__ontable">
      <el-collapse class="collapse">
        <el-collapse-item title="条件查询">
          <!-- 搜索输入框 -->
          <div class="search-holder">
            <el-row :gutter="20">
              <el-col :span="4">
                <el-input
                  v-model="searchVal.name"
                  placeholder="商品名称/模糊查询"
                />
              </el-col>
              <el-col :span="4">
                <el-input
                  v-model="searchVal.productSn"
                  placeholder="商品货号"
                />
              </el-col>
              <el-col :span="4">
                <el-select v-model="searchVal.brandId" placeholder="品牌">
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="searchVal.publishStatus"
                  placeholder="上架状态"
                >
                  <el-option
                    v-for="item in shelvesStatus"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="searchVal.verifyStatus"
                  placeholder="审核状态"
                >
                  <el-option
                    v-for="item in examineStatus"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="search">查询</el-button>
              </el-col>
            </el-row>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <el-button v-btn-permi:add type="primary" size="mini" @click="add">新增</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="exportExcel"
        >导出excel表格</el-button>
      </div>
      <div class="table-box">
        <!-- 商品展示表格 -->
        <el-table :data="productList" border style="width: 100%">
          <el-table-column fixed="left" type="index" label="#" width="50" />
          <el-table-column label="商品图片" width="200">
            <template slot-scope="scope">
              <img class="image" :src="scope.row.pic" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" width="200" />
          <el-table-column label="商品价格" width="200">
            <template slot-scope="scope">
              <p>原价:{{ scope.row.originalPrice }}</p>
              <p>现价:{{ scope.row.price }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="productCategoryName" label="商品类别" />
          <el-table-column label="标签1" width="200">
            <template slot-scope="scope">
              <div>
                最新
                <el-switch
                  v-model="scope.row.newStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="switchNew($event, scope.row.id)"
                />
              </div>
              <div>
                推荐
                <el-switch
                  v-model="scope.row.recommendStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="switchRecommand($event, scope.row.id)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="标签2" width="200">
            <template slot-scope="scope">
              <div>
                发布
                <el-switch
                  v-model="scope.row.publishStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="switchPublish($event, scope.row.id)"
                />
              </div>
              <div>
                审核
                <el-switch
                  v-model="scope.row.verifyStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="switchVerify($event, scope.row.id)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="sku" width="200">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="default"
                @click="editSku(scope.row.id)"
              >编辑sku</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量" />
          <el-table-column prop="sort" label="排序" />
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="edit(scope.row.id)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="mini"
                @click="del(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination-holder">
        <el-pagination
          :current-page="page.start"
          :page-sizes="page.pageSize"
          :page-size="page.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog title="编辑sku" :visible.sync="dialogTableVisible">
      <div class="table-holder">
        <el-button
          type="primary"
          size="default"
          @click="addSku"
        >新增</el-button>

        <!-- sku表格 -->
        <el-table
          v-if="skuList.length > 0"
          :data="skuList"
          border
          style="width: 100%"
        >
          <el-table-column fixed="left" type="index" label="序号" width="50" />
          <el-table-column label="图片" width="150">
            <template slot-scope="scope">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="
                  (res, file) => {
                    return tableUploadSuccess(res, file, scope.row.skuCode)
                  }
                "
              >
                <img v-if="scope.row.pic" :src="scope.row.pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="颜色" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.spData[0].value"
                placeholder="请输入颜色"
              />
            </template>
          </el-table-column>
          <el-table-column label="大小" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.spData[1].value"
                placeholder="请输入大小"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存" width="150">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.stock"
                placeholder="自定义库存"
              />
            </template>
          </el-table-column>
          <el-table-column label="预警库存" width="150">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.lowStock"
                placeholder="自定义预警库存"
              />
            </template>
          </el-table-column>
          <el-table-column label="锁定库存" width="150">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.lockStock"
                placeholder="自定义锁定库存"
              />
            </template>
          </el-table-column>
          <el-table-column label="sku编码" width="200">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.skuCode"
                placeholder="自定义sku编码"
              />
            </template>
          </el-table-column>
          <el-table-column label="价格" width="150">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.price"
                placeholder="自定义价格"
              />
            </template>
          </el-table-column>
          <el-table-column label="销量" width="150">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.sale"
                placeholder="自定义销量"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                v-btn-permi:edit
                type="text"
                size="default"
                @click="editSkuTableRow(scope.row)"
              >编辑</el-button>
              <el-button
                v-btn-permi:remove
                style="color: red"
                type="text"
                size="default"
                @click="delSkuTableRow(scope.row.skuCode)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  requestProductList,
  requestBrandList,
  deleteProduct,
  switchNewStatus,
  switchPublishStatus,
  switchRecommandStatus,
  switchVerifyStatus,
  requestSkuInfo,
  deleteSku,
  updateSkuInfo,
  addSkuInfo
} from '@/api/product'
import mixin from '@/mixins/index'
export default {
  mixins: [mixin],
  data() {
    return {
      productId: '',
      // 暂修改商品sku信息
      skuList: [],
      // 对话框显示
      dialogTableVisible: false,
      // 商品列表
      productList: [],
      // 品牌列表
      brandList: [],
      // 搜索框信息
      searchVal: {
        'brandId': '',
        'name': '',
        'productCategoryId': '',
        'productSn': '',
        'publishStatus': '',
        'verifyStatus': ''
      },
      // 上架状态列表
      shelvesStatus: [
        { name: '下架', value: 0 },
        { name: '上架', value: 1 }
      ],
      // 审核状态列表
      examineStatus: [
        { name: '未审核', value: 0 },
        { name: '审核通过', value: 1 }
      ]
    }
  },
  created() {
    console.log(this.page)
    this.getProductList()
    this.getBrandList()
  },
  methods: {
    // 导出excel
    exportExcel() {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['商品名称', '商品品牌', '商品价格']
        const keyList = ['name', 'brandName', 'price']
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data: this.screenExcelData(keyList), // 具体数据 必填
          filename: '商品列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 根据excel表格头筛选数据
    screenExcelData(keyList) {
      const list = []
      this.productList.forEach(val => {
        const arr = []
        keyList.forEach(keyVal => {
          arr.push(val[keyVal])
        })
        list.push(arr)
      })
      console.log(list)
      return list
    },
    // 新增sku
    addSku() {
      let spData = [{
        key: '颜色',
        value: ''
      }, {
        key: '大小',
        value: ''
      }]
      spData = JSON.stringify(spData)
      addSkuInfo({ spData, productId: this.productId }).then(res => {
        console.log(res)
      })
      this.getSkuList(this.productId)
    },
    // 编辑保存sku
    editSkuTableRow(item) {
      const obj = { ...item }
      obj.spData = JSON.stringify(obj.spData)
      updateSkuInfo(obj).then(res => {
        console.log(res)
        if (res.code === 20000) {
          this.$message({
            message: '更新商品sku成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '更新商品sku失败',
            type: 'error'
          })
        }
      })
    },
    // 删除sku表格行
    delSkuTableRow(id) {
      this.$confirm('此操作将删除该库存信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteSku(id).then((res) => {
            // console.log(res);
            if (res.code === 20000) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getSkuList(id)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 表格上传图片
    tableUploadSuccess(res, file, skuCode) {
      console.log(res, file, skuCode)
      this.skuList.forEach(val => {
        (val.skuCode === skuCode) && (this.$set(val, 'pic', res.data.fileUrl))
      })
    },
    // 判断修改状态
    isSuccess(code) {
      if (code === 20000) {
        this.$message({
          message: '修改状态成功',
          type: 'success'
        })
      } else {
        this.$message({
          message: '修改状态失败',
          type: 'error'
        })
      }
    },
    // 更改发布状态
    switchPublish(e, id) {
      console.log(e, id)
      switchPublishStatus({ productId: id, status: e }).then(res => {
        this.isSuccess(res.code)
        this.getProductList()
      })
    },
    // 更改是否推荐
    switchRecommand(e, id) {
      console.log(e, id)
      switchRecommandStatus({ productId: id, status: e }).then(res => {
        this.isSuccess(res.code)
        this.getProductList()
      })
    },
    // 更改审核状态
    switchVerify(e, id) {
      console.log(e, id)
      switchVerifyStatus({ productId: id, status: e }).then(res => {
        this.isSuccess(res.code)
        this.getProductList()
      })
    },
    // 更改是否最新
    switchNew(e, id) {
      console.log(e, id)
      switchNewStatus({ productId: id, status: e }).then(res => {
        this.isSuccess(res.code)
        this.getProductList()
      })
    },
    // 获取商品数据
    getProductList() {
      requestProductList(this.page, this.removeBlock(this.searchVal)).then((res) => {
        // console.log(res)
        this.productList = res.data.rows
        this.page.total = res.data.total
      })
    },
    // 获取品牌列表
    getBrandList() {
      requestBrandList().then(res => {
        // console.log(res)
        this.brandList = res.data.items
      })
    },
    // 搜索
    search() {
      this.page.start = 1
      this.getProductList()
    },
    // 重置搜索结果
    resetForm() {
      this.searchVal = {}
      this.getProductList()
    },
    // 获取sku信息
    getSkuList(id) {
      requestSkuInfo(id).then(res => {
        this.skuList = res.data.items ? res.data.items : []
        this.skuList.forEach(val => {
          val.spData = JSON.parse(val.spData)
        })
        this.skuList.forEach(val => {
          if (val.spData.length === 0) {
            val.spData.push({
              key: '颜色',
              value: ''
            }, {
              key: '大小',
              value: ''
            })
          } else if (val.spData.length === 1) {
            if (val.spData[0].key === '颜色') {
              val.spData.push({
                key: '大小',
                value: ''
              })
            } else if (val.spData[0].key === '大小') {
              val.spData.unshift({
                key: '颜色',
                value: ''
              })
            }
          }
        })
        console.log(this.skuList)
      })
    },
    // 编辑商品sku
    editSku(id) {
      this.productId = id
      this.getSkuList(id)
      this.dialogTableVisible = true
    },
    // 改变每页数量
    handleSizeChange(val) {
      this.page.limit = val
      this.getProductList()
    },
    // 改变页码
    handleCurrentChange(val) {
      this.page.start = val
      this.getProductList()
    },
    // 跳转到新增商品页面
    add() {
      this.$router.push('/product/addDetail')
    },
    // 跳转到编辑页面
    edit(id) {
      this.$router.push({ name: 'ProductEditDetail', params: { id }})
    },
    // 删除商品
    del(id) {
      console.log(id)
      const _this = this
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteProduct(id).then((res) => {
            // console.log(res);
            if (res.code === 20000) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              _this.getProductList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style lang="scss" scoped>
.product-list {
  .collapse {
    box-sizing: border-box;
    padding: 10px;
    background-color: #fff;
  }

  .collapse__ontable {
    padding: 20px 30px 0;
  }

  .image {
    width: 100px;
    height: 100px;
  }
}
</style>
